package com.tdam2011.grupo05.ui.activities.config.account;

import com.tdam2011.grupo05.R;
import com.tdam2011.grupo05.control.app.TdamApplication;
import com.tdam2011.grupo05.entities.account.Account;
import com.tdam2011.grupo05.processor.RegisterUserProcessor;
import com.tdam2011.grupo05.services.MessageService;
import com.tdam2011.grupo05.services.ServiceHelper;
import com.tdam2011.grupo05.services.constant.ServiceActions;
import com.tdam2011.grupo05.utils.preference.PreferencesHelper;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
 * Registra una nueva cuenta
 * TODO: refactoring completo
 * @author martin
 *
 */
public class AccountActivity extends Activity {

	private static final String TAG = "AccountActivity";

	private final static IntentFilter REGISTER_USER_FILTER = new IntentFilter();

	static {
		REGISTER_USER_FILTER.addAction(ServiceActions.REGISTER_USER_ACTION);
	}

	private TextView mTextViewUsuario;
	private TextView mTextViewPass;
	private TextView mTextViewRePass;
	private Button mButtonGuardar;
	private Button mButtonCancelar;
	private ProgressDialog mProgressDialog;
	private final Handler mHandler = new Handler();
	private String user;
	private String pass;

	private ServiceHelper mServiceHelper;
	private Account account;

	private View.OnClickListener saveAction = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			check();
		}
	};

	private View.OnClickListener cancelAction = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			cancel();
		}

	};

	private LocalBroadcastManager localBroadcast;

	private BroadcastReceiver registerUserReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ServiceActions.REGISTER_USER_ACTION.equals(action)) {
				if (intent.getBooleanExtra(RegisterUserProcessor.HAVE_ERROR,
						false)) {
					final int id = intent.getExtras().getInt(
							RegisterUserProcessor.ERROR_ID, -1);
					final StringBuffer detail = new StringBuffer();
					if (id == 5) {
						account = mServiceHelper.getDataManager().get(user);
						if (account != null) {
							detail.append(intent.getExtras().getString(
									RegisterUserProcessor.ERROR)
									+ " Ya existe Usuario");
							errorAccount(detail);
						} else {
							setAccount();
						}

					} else if (id == 12) {
						detail.append(intent.getExtras().getString(
								RegisterUserProcessor.ERROR)
								+ " Nombre mal formado");
						errorAccount(detail);
					} else {
						detail.append(intent.getExtras().getString(
								RegisterUserProcessor.ERROR)
								+ " Error inesperado");
						errorAccount(detail);
					}

				} else {
					setAccount();
				}
			}
		}
	};

	private void cancel() {
		setResult(RESULT_CANCELED, getIntent());
		finish();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cuenta);
		localBroadcast = LocalBroadcastManager.getInstance(this);

		localBroadcast.registerReceiver(registerUserReceiver,
				REGISTER_USER_FILTER);

		final Intent service = new Intent(this, MessageService.class);
		service.setAction(ServiceActions.START_SERVICE);
		startService(service);

		mServiceHelper = ServiceHelper.getIntance(this);

		mTextViewUsuario = (TextView) findViewById(R.id.txt_usuario_cuenta);
		mTextViewPass = (TextView) findViewById(R.id.txt_pass_cuenta_1);
		mTextViewRePass = (TextView) findViewById(R.id.txt_pass_cuenta_2);
		mButtonGuardar = (Button) findViewById(R.id.btn_guardar_cuenta);
		mButtonCancelar = (Button) findViewById(R.id.btn_cancelar_cuenta);
		mButtonGuardar.setOnClickListener(saveAction);
		mButtonCancelar.setOnClickListener(cancelAction);

	}

	private void check() {
		pass = mTextViewPass.getText().toString();
		user = mTextViewUsuario.getText().toString();
		if (!checkPass(pass, mTextViewRePass.getText().toString())) {
			showDialog(
					getResources().getString(R.string.dialog_error_title),
					getResources().getString(
							R.string.dialog_register_error_password_not_match));
		} else if (user.equals("") && user.length() > 5 && user.length() < 12) {
			showDialog(
					getResources().getString(R.string.dialog_error_title),
					getResources().getString(
							R.string.dialog_register_error_user_length));
		} else {
			mProgressDialog = new ProgressDialog(AccountActivity.this);
			mProgressDialog.setTitle(AccountActivity.this.getResources()
					.getString(R.string.progress_dialog_wait_message));
			mProgressDialog.setMessage(AccountActivity.this.getResources()
					.getString(R.string.progress_dialgo_account_checkin));
			mProgressDialog.show();
			mProgressDialog.setCancelable(false);
			mServiceHelper.registerAccount(user, pass);
		}
	}

	private void save() {
		pass = mTextViewPass.getText().toString();
		user = mTextViewUsuario.getText().toString();
		Log.d(TAG, "saving user=" + user + " pass=" + pass);
		final Intent intent = getIntent();
		intent.putExtra(PreferencesHelper.KEY_USERNAME, user);
		intent.putExtra(PreferencesHelper.KEY_PASSWORD, pass);
		setResult(RESULT_OK, intent);
		finish();
	}

	private void showDialog(String title, String message) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(title);
		alert.setMessage(message);
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				mTextViewRePass.setText("");
				mTextViewPass.setText("");
			}
		}).create().show();
	}

	private boolean checkPass(String pass, String rep) {
		return pass.equalsIgnoreCase(rep);
	}

	@Override
	public void finish() {
		localBroadcast.unregisterReceiver(registerUserReceiver);
		super.finish();
	}

	private void errorAccount(final StringBuffer detail) {
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				mProgressDialog.dismiss();
				showDialog(getResources()
						.getString(R.string.dialog_error_title), detail
						.toString());
			}
		});
	}

	private void setAccount() {
		account = new Account();
		account.setPassword(user);
		account.setUsername(pass);
		account.setLastSync(0);
		account.setId(mServiceHelper.saveNewAccount(account));
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				((TdamApplication) getApplication())
						.updateCurrentAccount(account);
				mProgressDialog.dismiss();
				save();
			}
		});
	}

}
